package com.jinglvhuanjing.app.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.NonNull;


import java.util.ArrayList;


public class SqlLiteHelper extends SQLiteOpenHelper {

    private SQLiteDatabase mSqLiteDatabase;
    public static volatile SqlLiteHelper instance;

    public synchronized static SqlLiteHelper getInstance(@NonNull Context context) {
        if (instance == null) {
            synchronized (SqlLiteHelper.class) {
                if (instance == null) {
                    instance = new SqlLiteHelper(context);
                }
            }
        }
        return instance;
    }

    private SqlLiteHelper(Context context) {
        super(context, SqlConfig.CONFIG_DB_NAME, null, SqlConfig.CONFIG_DB_VERSION);
        try {
            this.mSqLiteDatabase = super.getWritableDatabase();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @NonNull
    public SQLiteDatabase getSqLiteDatabase() {
        if (mSqLiteDatabase == null) {
            throw new NullPointerException("Please Check the register method is invoked!");
        }
        return mSqLiteDatabase;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        ArrayList<String> strings = SqlConfig.getCreateTableSql();
        if (!strings.isEmpty()) {
            for (String sql : strings) {
                sqLiteDatabase.execSQL(sql);
            }
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        ArrayList<String> strings = SqlConfig.getDropTablesSql();
        if (!strings.isEmpty()) {
            for (String sql : strings) {
                sqLiteDatabase.execSQL(sql);
            }
        }
        this.onCreate(sqLiteDatabase);
    }

    /**
     * 删除所有数据库记录
     */
    public void delete(@NonNull Context context) {
        try {
            ParamHelper.delete(context);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() {
        super.close();
        if (getReadableDatabase().isOpen()) {
            getReadableDatabase().close();
        }
    }
}